package com.csi.jf.crucible.common.util;

import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.chinasofti.ro.bizframework.core.json.jsonlib.processor.DateJsonValueProcessor;
import com.chinasofti.ro.bizframework.modules.json.JSONArray;
import com.chinasofti.ro.bizframework.modules.json.JSONObject;
import com.chinasofti.ro.bizframework.modules.json.JsonConfig;
import com.chinasofti.ro.bizframework.modules.json.ezmorph.object.DateMorpher;
import com.chinasofti.ro.bizframework.modules.json.util.JSONUtils;

public class JsonTools {

	/**
	 * @Title: JsonTools.java
	 * @Description: <br>
	 *               <br>
	 * @Company: Chinasofti
	 * @Created on 2014-7-9 
	 * @author JCJ
	 * @version $Revision: 1.0 $
	 * @since 1.0
	 */
	
	/**
	 * 将json串转成map
	 * 
	 * @param jsonStr
	 *            {"JGDM":"1029","ND":"2012","JD":"0","YD":"0","KMBM":"24","KMMC":"拨入作战经费","YEFX":"-1","KMLBMC":"","SJKMBM":"","KMLBBH":"","KMQC":"拨入作战经费","KMLB":"","KJNF":"","KMJC":"1"}
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> parseJSON2Map(String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 最外层解析
		JSONObject json = JSONObject.fromObject(jsonStr);
		for (Object k : json.keySet()) {
			Object v = json.get(k);
			// 如果内层还是数组的话，继续解析
			if (v instanceof JSONArray) {
				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				Iterator<JSONObject> it = ((JSONArray) v).iterator();
				while (it.hasNext()) {
					JSONObject json2 = it.next();
					list.add(parseJSON2Map(json2.toString()));
				}
				map.put(k.toString(), list);
			} else {
				map.put(k.toString(), v);
			}
		}
		return map;
	}

	/**
	 * 将json串转成map的List
	 * 
	 * @param jsonStr
	 *            [{"JGDM":"1029","ND":"2012","JD":"0","YD":"0","KMBM":"24","KMMC":"拨入作战经费","YEFX":"-1","KMLBMC":"","SJKMBM":"","KMLBBH":"","KMQC":"拨入作战经费","KMLB":"","KJNF":"","KMJC":"1"},{"JGDM":"1029","ND":"2012","JD":"0","YD":"0","KMBM":"25","KMMC":"拨入专项资金","YEFX":"-1","KMLBMC":"","SJKMBM":"","KMLBBH":"","KMQC":"拨入专项资金","KMLB":"","KJNF":"","KMJC":"1"},{"JGDM":"1029","ND":"2012","JD":"0","YD":"0","KMBM":"23","KMMC":"拨入政府专项经费","YEFX":"-1","KMLBMC":"","SJKMBM":"","KMLBBH":"","KMQC":"拨入政府专项经费","KMLB":"","KJNF":"","KMJC":"1"}]
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> parseJSON2List(String jsonStr) {
		JSONArray jsonArr = JSONArray.fromObject(jsonStr);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Iterator<JSONObject> it = jsonArr.iterator();
		while (it.hasNext()) {
			JSONObject json2 = it.next();
			list.add(parseJSON2Map(json2.toString()));
		}
		return list;
	}

	/**
	 * 将实体类对象转成json格式 {"id" : idValue, "name" : nameValue,"aBean" : {"aBeanId" : aBeanIdValue, ...}}
	 * @param obj 被转的实体类对象
	 * @param format 时间格式 "yyyy-MM-dd"
	 * @return
	 */
	public static String toJson(Object obj,String format) {
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor(format));  
        String json = JSONObject.fromObject(obj, config).toString();
		return json;
	}
	/**
     * 将实体类对象转成json格式 {"id" : idValue, "name" : nameValue,"aBean" : {"aBeanId" : aBeanIdValue, ...}}
     * 主要针对sql.Date/sql/Timestamp时间格式
     * @param obj 被转的实体类对象
     * @param format 时间格式 "yyyy-MM-dd"
     * @return
     */
    public static String listToJson(Object obj,String format) {
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor(format));
        config.registerJsonValueProcessor(Timestamp.class,new DateJsonValueProcessor(format)); 
        String json = JSONArray.fromObject(obj, config).toString();
        return json;
    }
	/**
	 * 从一个JSON 对象字符格式中得到一个java对象，形如： {"id" : idValue, "name" : nameValue,
	 * "aBean" : {"aBeanId" : aBeanIdValue, ...}}
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static Object getDTO(String jsonString, Class clazz) {
		JSONObject jsonObject = null;
		try {
			setDataFormat2JAVA();
			jsonObject = JSONObject.fromObject(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.toBean(jsonObject, clazz);
	}

	private static void setDataFormat2JAVA() {
		// 设定日期转换格式
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" }));
	}

	/**
	 * 将json字符串转化成某个 POJO类的list集合
	 * 
	 * @param <T>
	 * @param jsonString
	 * @param pojoClass
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws InstantiationException
	 */
	public static <T> List<T> toList(String jsonString, Class<T> pojoClass) throws IllegalAccessException, InvocationTargetException, InstantiationException {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		JSONObject jsonObject;
		List<T> list = new ArrayList();
		for (int i = 0; i < jsonArray.size(); i++) {
			jsonObject = jsonArray.getJSONObject(i);
			T t = pojoClass.newInstance();
			for (Object object : jsonObject.entrySet()) {
				Map.Entry entry = (Map.Entry) object;
				String propertyName = entry.getKey().toString();
				Object propertyValue = entry.getValue();
				BeanUtils.setProperty(t, propertyName, propertyValue);
			}
			list.add(t);
		}
		return list;
	}
	
}
